<template>
  <div class="main-wrapper">
    <div class="flex-container">
      <sceneLeft run_mode="log2world" :fromCreateTaskPage="fromCreateTaskPage"/>
      <div class="logsim-right width-col-18">
        <!-- 工具栏 -->
        <div class="search-wrap">
          <div class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters" size="small">
              <el-form-item>
                <el-input
                  v-model="filters.record_name"
                  clearable
                  placeholder="请输入Record名称"
                >
                </el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="operaution-btn-group">
            <!-- 从创建作业过来的， 不显示 添加到组 和 删除的按钮 -->
            <div v-show="!fromCreateTaskPage">
              <el-button
                  size="small"
                  type="primary"
                  :disabled="!selectedCount"
                  @click="_handleAddToGroup"
                >添加到组
              </el-button>
            </div>
          </div>
        </div>
        <MyTable 
          ref="log2worldTable"
          currentTable ="log2worldTable"
          :hasSelection="true"
          :idEnableSelection="idEnableSelection"
          :tableData="recordData" 
          :tableItem="columns"
          :total="total"
          @handlePageChange="handlePageChange"
          @selectionChange="handleSelectionChange"
          />
      </div>
    </div>
    <!--弹窗-->
    <AppendGroupDialog :showModal="isVisibleAppendGroupModal" :customGroups="customGroups" :selectNum="selectedCount" @closeDialog="_closeAppendDialog" @handleDialogSubmit="_submitAppend"/>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import {fetchLog2worldRecord, fetchCustomGroup, fetchGroupCase} from '@/api/case'
import  sceneLeft from '../components/sceneLeft.vue'
import MyTable from '@/components/MyTable'
import AppendGroupDialog from '@/components/AppendGroup'
import addToGroupMixin from '@/mixins/group/add_to_group'
const log2worldMixin = new addToGroupMixin('log2world')
export default {
    mixins: [log2worldMixin],
    components:{ sceneLeft, MyTable, AppendGroupDialog },
    data(){
      return{
        isVisibleAppendGroupModal: false,
        customGroups: [],
        recordData: [],
        columns:[
          {
            name: 'record名称',
            prop: 'record_name',
            width: ''
          },
        ],
        total: 0,
        pageIndex: 1,
        pageSize: 20,
        selectedRecords: [],
        selectedCount: 0,
        filters:{
          record_name:'',
        },
        idEnableSelection: true
      }
    },
    props:{
      fromCreateTaskPage: Boolean
    },
    computed: {
      ...mapState({
        caseIds: state => state.case.caseIds,
        treeIdForLog2world: state => state.scene.treeIdForLog2world,
        checkedCustomGroup: state => state.scene.checkedCustomGroup,
        isCommonCategory: state => state.scene.isCommonCategory,
        caseGroupIds: state => state.case.caseGroupIds,
        caseCategoryIds: state => state.case.caseCategoryIds,
      })
    },
    watch:{
      // 搜索
      filters:{
        deep:true,
        handler: function(){
          this.pageIndex = 1
          this.pageSize = 20
          this.getRecordList()
        }
      },
      // 当前点击的tree id，匹配选中的 category组 做判断，
      treeIdForLog2world:{
        handler(newVal){
          if(newVal) {
            this.pageIndex = 1
            this.pageSize = 20
            this.handleReset()
            setTimeout(() => {
              this.handleTreeAndTableSelection(this.caseCategoryIds,this.treeIdForLog2world)
              this.getRecordList()
            },1000)
          }
        }
      },
      // 当前选中的category 组，右侧列表重新获取， 匹配点击的tree id 做判断
      caseCategoryIds: {
        deep: true,
        handler(newVal){
          if(newVal){
            this.pageIndex = 1
            this.pageSize = 20
            setTimeout(() => {
              this.handleTreeAndTableSelection(this.caseCategoryIds,this.treeIdForLog2world)
              this.getRecordList()
            },1000)
          }
        }
      },
      // 当前点中的自定义组，右侧列表重新获取， 匹配选中的自定义组的id 做判断
      checkedCustomGroup: {
        deep: true,
        handler(newVal){
          if(!!newVal.id){
            this.pageIndex = 1
            this.pageSize = 20       
            setTimeout(() => {
              this.handleTreeAndTableSelection(this.caseGroupIds,this.checkedCustomGroup.id)
              this.getRecordList()
            },1000)
          }
        }
      },
      // 选中的自定义组，右侧列表重新获取， 匹配选中文字的自定义组的id 做判断
      caseGroupIds: {
        deep: true,
        handler(newVal){
          setTimeout(() => {
              this.handleTreeAndTableSelection(this.caseGroupIds,this.checkedCustomGroup.id)
              this.getRecordList()
            },1000)
        }
      }
    },
    mounted(){
       /* 
      初始化时：
      1. 将默认值置log2world
      2. 默认取category的数据
      3. 将之前点击选中的自定义组的id置为''
    */
      this.$store.dispatch('scene/updateTreeIdForLog2world', '')  
      this.$store.dispatch('scene/updateIsCommonCategory', true)
      this.$store.dispatch('scene/updateCheckedCustomGroup', {})
      this.getCustomGroup()
      this.getRecordList()
    },
    methods: {
      getRecordList(){
         // 点击默认标签组 的获取case
        if(this.isCommonCategory){  
          const params = {
            page_num: this.pageIndex,
            page_size: this.pageSize,
            run_mode: 'log2world',
            category_id: this.treeIdForLog2world || 1,
            record_name_pattern: this.filters.record_name
          }
          fetchLog2worldRecord(params).then(res => {
            // table数据需要加id ,用于在表格多选时候 checked显示正确
            if(res && res.data){
              this.recordData = res.data.map((item) => {
                return Object.assign(item,{id: item.record_name})
              })
              this.total = res.total
            }
            // 如果该页面是从创建作业调用过来的，则执行下面这行， 实现【上一步】时回显已勾选数据的功能
            if(this.fromCreateTaskPage){
              this.showbackSelection()
            }
          })
        }else{
           // 点击自定义组 的获case
          const groupParams = {
            page_num: this.pageIndex,
            page_size: this.pageSize,
            group_id: this.checkedCustomGroup.id
          }
          fetchGroupCase(groupParams).then(res => {
            // table数据需要加id ,用于在表格多选时候 checked显示正确
            if(res && res.data){
              this.recordData = res.data.map((item) => {
                return Object.assign(item,{id: item.case_id, record_name:item.case_id})
              })
              this.total = res.total
            }
            // 如果该页面是从创建作业调用过来的，则执行下面这行， 实现【上一步】时回显已勾选数据的功能
            if(this.fromCreateTaskPage){
              this.showbackSelection()
            }
          }).catch(err => {
            this.$message.error(err)
          })
        }
      },
      getCustomGroup(){
        fetchCustomGroup({run_mode: "log2world"}).then(res => {
          if(res.code === 0){
            this.customGroups = res.data
          }
        })
      },
       // 切换pagesize 、切换页码
      handlePageChange(pageData) {
        this.pageIndex = pageData.page_num
        this.pageSize = pageData.page_size
        this.getRecordList()
      },
      // 选择
      handleSelectionChange(val) {
        this.selectedRecords = val.map(item => {
          return item.id
        })
        this.selectedCount = this.selectedRecords.length
        // // 如果该页面是从创建作业调用过来的，则执行下面这行，将选中的case_id 存入store
        if(this.fromCreateTaskPage){
          this.$store.dispatch('case/setSelectedCaseIds', this.selectedRecords)
        }     
      },
      // 勾选数据回显到页面 
      showbackSelection(){
        this.$nextTick(()=> {
            this.caseIds.forEach(item => {
              this.recordData.forEach(row => {
              if(item === row.record_name){
                this.$refs.log2worldTable.$refs.myTable.toggleRowSelection(row,true)
              }
            })
          
          })
        })
      },
      handleReset(){
        this.filters.record_name = ''
      },
      // 左侧tree 和右侧列表的 对应关系判断，从而 判断右侧列表的选择框 可勾选/disabeld
      handleTreeAndTableSelection(selectArr,currentId){
        if(selectArr.indexOf(currentId) > -1){
          this.$nextTick(() => {
            this.idEnableSelection = false
          })
        }else{
          this.$nextTick(() => {
            this.idEnableSelection = true
          })
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .logsim-left-title{
    color: #293b5a;
    padding: 21.5px;
    font-size: 13px;
    font-family: Source Han Sans CN;
    font-weight: 600;
    border-bottom: 1px solid rgba(0, 0, 0, 0.12);
  }
  .logsim-left-ul{
    // padding: 20px;
    >li {
      padding: 10px 0;
      cursor: pointer;
      i{
        margin-left: 20px;
      }
      span {
        margin-left: 20px;
      }
      &.active{
        background-color: rgb(74, 144, 226);
        color: #fff;
      }
    }
  }
  .logsim-right .el-table{
    height: 1008px;
    overflow: auto;
  }
</style>
